home *** CD-ROM | disk | FTP | other *** search
- Path: news.sprintlink.net!datalytics!usenet
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++,comp.object,comp.object.logic
- Subject: Re: polymorphism
- Date: Mon, 25 Mar 1996 12:56:07 -0500
- Organization: Datalytics, Inc
- Message-ID: <3156DE37.4782@datalytics.com>
- References: <4j2k2b$4pj@arl-news-svc-3.compuserve.com>
- NNTP-Posting-Host: 204.62.224.71
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- .,@compuserve.com wrote:
- >
- > >>What is polymorphism.
- >
- > The usual example is a shape object.
- > Shape is your base class.
- > From this you derive the classes called Circle, Triangle, and Square.
- > Shape has a function called Draw()
- > So each of the 3 classes (Circle, Triangle, Square) redo the Draw() function
- > in there own way. Thus they all will be drawn differently from the others.
- > The compiler can handle this. The classes are said to be able
- > to draw themselves.
- > Note the Draw() must be identicle to the Shape classes Draw().
- > You can't change the argument list, this would be an overloaded
- > function and would not be the same function.
-
- This behavior only applies to virtual mfs. Here's an example to
- illustrate the point:
-
- Shape* pShape = 0;
- switch (shapeToDraw)
- {
- case CIRCLE:
- {
- pShape = new Circle;
- }
- break;
- case TRIANGLE:
- {
- pShape = new Triangle;
- }
- break;
- case SQUARE:
- {
- pShape = new Square;
- }
- break;
- }
- if (pShape)
- {
- pShape->Draw();
- }
-
- As you can see, this code uses a pointer to the base class
- (Shape) to invoke the Draw mf. The implementation invoked
- depends upon the type of the object to which pShape points. If
- shapeToDraw had the value CIRCLE, pShape->Draw() would invoke
- Circle::Draw().
-
- BTW, this also applies to references, except you can only
- initialize references. Therefore, the polymorphic behavior
- through a reference is normally limited to occassions in which a
- function has a reference to the base class. You can pass
- derived class objects to the function, invoking the correct
- derived class' virtual functions through that reference.
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc. | stew@datalytics.com
-